﻿using Newtonsoft.Json;
using SmartForm.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SmartlForm.Api
{
    public class ApiHelper
    {
        private static string ApiUrl = "http://sso.9ee3.com/";

        private static string ApiDomain
        {
            get
            {
                try
                {
                    Uri uri = new Uri(ApiUrl);
                    return uri.Host;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        public static LoginUserInfo LoginUser { get; set; }


        /// <summary>
        /// 访问Cookie
        /// </summary>
        private static CookieCollection Cookie = new CookieCollection();


        /// <summary>
        /// 设置登录账号信息
        /// </summary>
        public static ApiResult Login(string mobile = "", string password = "")
        {
            LoginUser = new LoginUserInfo();
            if (!string.IsNullOrEmpty(mobile))
                LoginUser.Mobile = mobile;
            if (!string.IsNullOrEmpty(password))
                LoginUser.Password = password;
            var result = SetLoginCookie();
            return result;
        }


        private static ApiResult SetLoginCookie()
        {
            //接口参数
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("mobile", LoginUser.Mobile);
            param.Add("password", LoginUser.Password);
            //请求接口
            ApiResult result = HttpPost("pass/login", param);
            if (result.ret == 200)
            {
                string token = result.data.token;
                Cookie.Add(new Cookie("token", token, "/", ApiDomain));
            }
            else
            {
                if (Cookie["token"] != null)
                    Cookie["token"].Value = null;
            }
            return result;
        }

        public static ApiResult GetLoginInfo(string token)
        {
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("token", token);
            ApiResult result = HttpPost("pass/checkToken", param);
            return result;
        }


        /// <summary>
        /// Get方式请求Api
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static ApiResult HttpGet(string url)
        {
            if (url.IndexOf("http:") == -1 && url.IndexOf("https:") == -1)
            {
                url = ApiUrl + url.TrimStart('/');
            }
            string result = HttpHelper.GetHttpResponse(url);
            var data = JsonConvert.DeserializeObject<ApiResult>(result);
            //Api登陆失效续约
            if (data.ret == 401)
            {
                //重新登录
                var loginResult = SetLoginCookie();
                if (loginResult.ret == 200)
                {
                    //重新请求接口
                    return HttpGet(url);
                }
            }
            return data;
        }

        /// <summary>
        /// Post方式请求Api
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <param name="cookie"></param>
        /// <param name="timeout"></param>
        /// <param name="userAgent"></param>
        /// <returns></returns>
        public static ApiResult HttpPost(string url, Dictionary<string, string> parameters = null, int timeout = 5000, string userAgent = "")
        {
            if (url.IndexOf("http:") == -1 && url.IndexOf("https:") == -1)
            {
                url = ApiUrl + url.TrimStart('/');
            }
            string result = HttpHelper.PostHttpResponse(url, parameters, timeout, userAgent, Cookie);
            Console.WriteLine("result：" + result);
            var data = JsonConvert.DeserializeObject<ApiResult>(result);
            //Api登陆失效续约
            if (data.ret == 401)
            {
                //重新登录
                var loginResult = SetLoginCookie();
                if (loginResult.ret == 200)
                {
                    //重新请求接口
                    return HttpPost(url, parameters, timeout, userAgent);
                }
            }
            return data;
        }



    }

    public class LoginUserInfo
    {
        /// <summary>
        /// 账号
        /// </summary>
        public string Mobile { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }

    }
}
